﻿using System;
using System.Collections;
using System.Threading;
using FlowCanvas;
using FlowCanvas.Nodes;
using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;
using Timer = System.Timers.Timer;

namespace Yoozoo.Gameplay.Liberty.Nodes
{
    [Category("Ggame")]
    public class AutoReqClaimBuildingReward:FlowControlNode
    {
        protected Coroutine co;
        [RequiredField]
        public BBParameter<int> buildingId;
        public BBParameter<int> buildingIndex;
        public BBParameter<int> targetBuildingLv;

        public IEnumerator Invoke(FlowOutput caseTrue, FlowOutput caseFalse, Flow f)
        {
            yield return new WaitForSeconds(0.3f);
            bool isArrivedeTargetLv = BlueprintUtils.AutoReqClaimBuildingReward(buildingId.value, buildingIndex.value,targetBuildingLv.value);
            f.Call(isArrivedeTargetLv ? caseTrue : caseFalse);
            
            while (!isArrivedeTargetLv)
            {
                yield return new WaitForSeconds(0.5f);
                isArrivedeTargetLv = BlueprintUtils.AutoReqClaimBuildingReward(buildingId.value, buildingIndex.value,targetBuildingLv.value);
                f.Call(isArrivedeTargetLv ? caseTrue : caseFalse);
            }
            
            co = null;
        }
        
        protected override void RegisterPorts()
        {
            var caseTrue = AddFlowOutput("True");
            var caseFalse = AddFlowOutput("False");
            var caseThen = AddFlowOutput("Then");
            AddFlowInput("In", (f) =>
            {
                BlueprintUtils.AutoReqClaimBuildingReward(buildingId.value, buildingIndex.value,targetBuildingLv.value);
                co = StartCoroutine(Invoke(caseTrue,caseFalse,f));
                f.Call(caseThen);
            });

        }
        
        public override void OnGraphStoped()
        {
            base.OnGraphStoped();
            if (co!=null)
            {
                StopCoroutine(co);
            }
        }
        
    }
}